﻿/*****************************************介绍*****************************************
 * 作者：24531
 * 创建时间：2025-08-31 15:39:41
 * 功能：IOS构建后处理
 *      1、修改Info.plist文件，添加自定义参数
**************************************************************************************/

#if UNITY_IOS
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.iOS.Xcode;
using UnityEngine;

public class IOSPostProcessBuild : IPostprocessBuildWithReport
{
    public int callbackOrder => 999;

    public void OnPostprocessBuild(BuildReport report)
    {
        if (report.summary.platform != BuildTarget.iOS) return;

        string projectPath = report.summary.outputPath;

        ModifyInfoPlist(projectPath);

        ModifyUnityFramework(projectPath);
    }

    private void ModifyUnityFramework(string path)
    {
        string projectPath = PBXProject.GetPBXProjectPath(path);
        PBXProject project = new PBXProject();
        project.ReadFromFile(projectPath);

        // 获取UnityFramework targetGUID
        string targetGUID = project.GetUnityFrameworkTargetGuid();

        // 添加Photos.framework
        project.AddFrameworkToProject(targetGUID, "Photos.framework", false);

        // 写入修改到项目文件
        project.WriteToFile(projectPath);
    }

    private void ModifyInfoPlist(string projectPath)
    {
        string plistPath = Path.Combine(projectPath, "Info.plist");
        if (!File.Exists(plistPath))
        {
            Debug.LogError("❌ Info.plist 不存在，无法修改。");
            return;
        }

        PlistDocument plist = new PlistDocument();
        plist.ReadFromFile(plistPath);
        PlistElementDict rootDict = plist.root;

        // 在 Assets 目录下递归查找任意 Editor 文件夹中的 plist.xml
        string[] configFiles = Directory.GetFiles(Application.dataPath, "plist.xml", SearchOption.AllDirectories);
        string configPath = null;
        foreach (string file in configFiles)
        {
            if (file.Replace("\\", "/").Contains("/Editor/"))
            {
                configPath = file;
                break;
            }
        }

        if (string.IsNullOrEmpty(configPath))
        {
            Debug.LogError("❌ 没有找到有效的 plist.xml 配置文件（需放在任意 Editor 文件夹下）。");
            return;
        }

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(configPath);
        XmlNodeList items = xmlDoc.SelectNodes("//plist/item");

        foreach (XmlNode item in items)
        {
            if (item.Attributes["key"] != null && item.Attributes["value"] != null)
            {
                string key = item.Attributes["key"].Value;
                string value = item.Attributes["value"].Value;
                rootDict.SetString(key, value);
                Debug.Log("✅ 添加配置：" + key + " = " + value);
            }
        }

        plist.WriteToFile(plistPath);
        Debug.Log("✅ Info.plist 修改成功，已根据 " + configPath + " 添加配置");
    }
}
#endif